//
//  TZSystemDetailController.m
//  DemoProduct
//
//  Created by 谭真 on 16/1/21.
//  Copyright © 2016年 iCE. All rights reserved.
//

#import "TZWebViewController.h"
#import "WebViewJavascriptBridge.h"



@interface TZWebViewController ()<UIWebViewDelegate> {
    BOOL _showWebTitle;
}
@property (nonatomic, strong) UIWebView *webView;
@property WebViewJavascriptBridge *bridge;
@property (nonatomic, strong) UIActivityIndicatorView *activityView;
@property (nonatomic, strong) UILabel *tipLable;
@end

@implementation TZWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (!self.navigationItem.title.length) {
        self.navigationItem.title = @"加载中...";
        _showWebTitle = YES;
    }
    
    [self configWebView];
    [self configActivityView];
    [self initWebViewJavascriptBridge];
    [self setupLeftBarButtonItems];
}

- (void)configWebView {
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, mScreen_W, mScreen_H - NavBar_H)];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_link_url]];
    [_webView loadRequest:request];
    _webView.scalesPageToFit = YES;
    _webView.delegate = self;
    [self.view addSubview:_webView];
}

- (void)setupLeftBarButtonItems {
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_hong"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"message_close"] style:UIBarButtonItemStyleDone target:self action:@selector(close)];
    if ([_webView canGoBack]) {
        self.navigationItem.leftBarButtonItems = @[backItem,closeItem];
    } else {
        self.navigationItem.leftBarButtonItem = backItem;
    }
}

- (void)configActivityView {
    _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityView.frame = CGRectMake(mScreen_W / 2 - 15 - 40, mScreen_H / 2 - 20 - 64, 40, 40);
    [self.view addSubview:_activityView];
    
    _tipLable  = [[UILabel alloc] init];
    _tipLable.frame = CGRectMake(mScreen_W / 2 - 15, mScreen_H / 2 - 20 - 64, 70, 40);
    _tipLable.text = @"加载中...";
    _tipLable.textColor = [UIColor lightGrayColor];
    [self.view addSubview:_tipLable];
}

- (void)initWebViewJavascriptBridge {
    if (_bridge) { return; }
    [WebViewJavascriptBridge enableLogging];
    // 0.建桥接
    _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(@"Response for message from ObjC");
    }];
    // 1.预览大图
    [_bridge registerHandler:@"showImage" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSArray *imgs = data[@"imgs"];
        NSMutableArray *items = [NSMutableArray new];
//        for (NSUInteger i = 0 ; i < imgs.count ; i++) {
//            MJPhoto *photo = [[MJPhoto alloc] init];
//            photo.url = [NSURL URLWithString:imgs[i]];
//            [items addObject:photo];
//        }
//        MJPhotoBrowser *photoBrowser = [[MJPhotoBrowser alloc] init];
//        photoBrowser.photos = items;
//        photoBrowser.currentPhotoIndex = [data[@"index"] integerValue];
        // [photoBrowser showWithContentView:self.navigationController.view];
    }];
}

#pragma mark - 点击事件
- (void)back {
    if (_webView.canGoBack) {
        [_webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)close {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIWebViewDelegate

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [_activityView startAnimating];
    _tipLable.hidden = NO;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"网页加载失败");
    [_activityView stopAnimating];
    _tipLable.hidden = YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [_activityView stopAnimating];
    
    
    // 获取图片大于屏幕宽度 取为屏幕宽度 否则为自己宽度
    NSString *js=@"var script = document.createElement('script');"
    "script.type = 'text/javascript';"
    "script.text = \"function ResizeImages() { "
    "var myimg,oldwidth;"
    "var maxwidth = %f;"
    "for(i=0;i <document.images.length;i++){"
    "myimg = document.images[i];"
    "if(myimg.width > maxwidth){"
    "oldwidth = myimg.width;"
    "myimg.width = %f;"
    "}"
    "}"
    "}\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    js=[NSString stringWithFormat:js,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width-15];
    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    
    
    _tipLable.hidden = YES;
    if (_showWebTitle) {
        self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }
    [self setupLeftBarButtonItems];
}

@end
